package com.superzlc.miniweb.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import com.superzlc.miniweb.comn.Configuation;
import com.superzlc.miniweb.comn.Util;
import com.superzlc.miniweb.servlet.anno.Controller;
import com.superzlc.miniweb.servlet.anno.QueryParam;
import com.superzlc.miniweb.servlet.anno.RequestMapping;

@Controller
public class FileScan {

	private static String encode = "UTF-8";

	@RequestMapping(value="/filescan")
	public void filescan1(HttpServletResponse response, @QueryParam("dirkey") String dirkey, @QueryParam("path") String extPath) throws ServletException, IOException {
		String basePath = getScanHome(dirkey);
		if (basePath == null) {
			response.sendError(900, extPath + " - 没配置scan_home或scan_home.*");
			return;
		}
		_filescan(response, dirkey, basePath, extPath);
	}

	//
	private void _filescan(HttpServletResponse response, String dirkey, String basePath, String extPath) throws ServletException, IOException {
		if (dirkey == null)
			dirkey = "";
		if (extPath == null) {
			extPath = "";
		} else {
			extPath = new String(extPath.getBytes("ISO-8859-1"), encode);
		}
		if (extPath.contains("..")) {
			response.sendError(900, extPath + " - 不允许查看包含..的路径的文件夹");
		}
		File file = new File(basePath + File.separator + extPath);
		// String path = file.getAbsolutePath();

		if (!file.exists()) {
			response.sendError(900, extPath + " - 文件不存在");
			return;
		}
		if (file.isFile()) {
			Util._download(response, file);
			return;
		}
		if (!file.isDirectory()) {
			response.sendError(900, extPath + " - 不是文件夹");
			return;
		}
		// 显示目录
		PrintWriter writer = response.getWriter();
		File[] files = file.listFiles();

		String style = "<style>"
				+ "a{ text-decoration: none;}"
				+ "a:hover{txt-decoration:underline;}"
				+ "</style>\n";
		writer.write(style);
		writer.write("路径：" + extPath + "<br/>\n");
		writer.write("总共" + files.length + "个文件<br/>\n");
		writer.write("<hr/>\n");
		writer.write("<table>\n");
		String format = "<tr><td>%s</td><td style='text-align:right;width:120px'>%s</td><td><a href='?dirkey=%s&path=%s'>%s</a></td></tr>";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String filetime = null;
		String filelength = null;
		String filename = null;
		String fileurl = null;

		File parentfile = file.getParentFile();
		String parentfilepath = parentfile.getPath();
		if (parentfilepath.length() >= basePath.length()) {
			filename = "..";
			filetime = sdf.format(new Date(parentfile.lastModified()));
			filelength = "&lt;DIR&gt;";
			fileurl = parentfilepath.substring(basePath.length());
			fileurl = URLEncoder.encode(fileurl, encode);
			writer.write(String.format(format, filetime, filelength, dirkey, fileurl, filename));
		}
		for (int j = 0; j < files.length; j++) {
			File tfile = files[j];
			filename = tfile.getName();
			filetime = sdf.format(new Date(tfile.lastModified()));
			fileurl = tfile.getPath().substring(basePath.length());
			fileurl = URLEncoder.encode(fileurl, encode);
			if (tfile.isDirectory()) {
				filelength = "&lt;DIR&gt;";
			} else if (tfile.isFile()) {
				long length = tfile.length();
				// B KB MB GB TB
				filelength = getFileLength(length);
			} else {
				filelength = "&lt;UNKNOWN&gt;";
			}
			writer.write(String.format(format, filetime, filelength, dirkey, fileurl, filename));
		}
		writer.write("</table>\n");
	}

	//
	@RequestMapping(value="/superfilescan")
	public void superfilescan(HttpServletResponse response, @QueryParam("dirkey") String dirkey, @QueryParam("path") String path) throws ServletException, IOException {
		if (dirkey == null)
			dirkey = "";
		if (path == null) {
			path = ".";
		} else {
			path = new String(path.getBytes("ISO-8859-1"), encode);
		}
		File nowfile = new File(path);

		if (!nowfile.exists()) {
			response.sendError(900, nowfile + "文件不存在");
			return;
		}
		if (nowfile.isFile()) {
			// Util._download(response, nowfile);
			response.sendError(200, nowfile + "是文件, 不支持下载");
			return;
		}
		if (!nowfile.isDirectory()) {
			response.sendError(900, nowfile + "不是文件夹");
			return;
		}
		// 显示目录
		PrintWriter writer = response.getWriter();
		File[] files = nowfile.listFiles();

		String style = "<style>"
				+ "a{ text-decoration: none;}"
				+ "a:hover{txt-decoration:underline;}"
				+ "</style>\n";
		writer.write(style);
		writer.write("路径：" + path + "<br/>\n");
		writer.write("总共" + files.length + "个文件<br/>\n");
		writer.write("<hr/>\n");
		writer.write("<table>\n");
		String format = "<tr><td>%s</td><td style='text-align:right;width:120px'>%s</td><td><a href='?dirkey=%s&path=%s'>%s</a></td></tr>";
		String format1 = "<tr><td>%s</td><td style='text-align:right;width:120px'>%s</td><td>%s</td></tr>";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String filetime = null;
		String filelength = null;
		String filename = null;
		String fileurl = null;

		File parentfile = nowfile.getParentFile();
		if (parentfile != null) {
			filename = "..";
			filetime = sdf.format(new Date(parentfile.lastModified()));
			filelength = "&lt;DIR&gt;";
			fileurl = parentfile.getPath();
			fileurl = URLEncoder.encode(fileurl, encode);
			writer.write(String.format(format, filetime, filelength, dirkey, fileurl, filename));
		}
		for (int j = 0; j < files.length; j++) {
			File tfile = files[j];
			filename = tfile.getName();
			filetime = sdf.format(new Date(tfile.lastModified()));
			fileurl = tfile.getPath();
			fileurl = URLEncoder.encode(fileurl, encode);
			if (tfile.isDirectory()) {
				filelength = "&lt;DIR&gt;";
			} else if (tfile.isFile()) {
				long length = tfile.length();
				// B KB MB GB TB
				filelength = getFileLength(length);
				fileurl = null;
			} else {
				filelength = "&lt;UNKNOWN&gt;";
			}
			String trrrr;
			if (fileurl == null) {
				trrrr = String.format(format1, filetime, filelength , filename);
			} else {
				trrrr = String.format(format, filetime, filelength, dirkey, fileurl, filename);
			}
			writer.write(trrrr);
		}
		writer.write("</table>\n");
	}

	//
	public static String getScanHome(String dirkey) {
		if (dirkey == null || dirkey.length() == 0)
			dirkey = "scan_home";
		else
			dirkey = "scan_home." + dirkey;
		String path = Configuation.getString(dirkey);
		if (path == null)
			return null;
		return new File(path).getAbsolutePath();
	}

	public static String getFileLength(long length) {
		if (length < 1024) {
			return String.valueOf(length) + "  B";
		}
		if (length < 1024 * 1024) {
			return String.valueOf(length / 1024f) + " KB";
		}
		if (length < 1024 * 1024 * 1024) {
			return String.valueOf(length / (1024f * 1024f)) + " MB";
		}
		return String.valueOf(length / (1024f * 1024f * 1024f)) + " GB";
	}

}
